<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>后台管理中心</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <link href="https://info.l3y.vip/css/app.css" rel="stylesheet">
    <link href="https://info.l3y.vip/js/layui/css/layui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://info.l3y.vip/js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="https://info.l3y.vip/js/layer/layer.js"></script>
    <script type="text/javascript" src="https://info.l3y.vip/js/layui/layui.js"></script>
    <link rel="stylesheet" href="/css/element.v2.css">
</head>

<body>
    <div id="app">
        <div class="wrapper -header-fixed">
            @include('admin.layouts.navbar')
            @include('admin.layouts.sidebar')

            <div class="content-container">
                <div class="container-fluid">
                    <div class="page-content">
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">仪表盘</a></li>
                                <li class="breadcrumb-item active" aria-current="page">登录充值统计</li>
                            </ol>
                        </nav>

                        <div class="card">
                            <div class="card-body">
                                <div class="content-box">
                                    <div class="op-bar" style="margin: 16px 0;">
                                        日期：
                                        <input type="text" id="date" placeholder="请选择日期" class="layui-input" style="width: 360px; display: inline-block;">
                                        <button class="layui-btn layui-btn-primary" id="searchBtn">统计</button>
                                    </div>

                                    <div id="charts" style="display: flex; flex-wrap: wrap;">
                                        <div id="pieChart" style="width: 48%; height: 400px; margin: 1%"></div>
                                        <div id="loginPieChart" style="width: 48%; height: 400px; margin: 1%"></div>
                                        <!--<div id="dayBarChart" style="width: 48%; height: 400px; margin: 1%"></div>-->
                                        <div id="recentGamesBarChart" style="width: 48%; height: 400px; margin: 1%"></div>
                                        <!--<div id="redPacketChart" style="width: 48%; height: 400px; margin: 1%"></div>-->
                                        <div id="monthlyBarChart" style="width: 48%; height: 400px; margin: 1%"></div>
                                        <div id="totalRechargeChart" style="width: 100%; height: 400px; margin: 1%"></div>
                                    </div>

                                    <div class="statistics-box" style="margin: 16px 0;">
                                        <h3>当天消费情况</h3>
                                        <p>当天充值消费大于20元人数: <span id="highSpenders20"></span> (占比: <span id="percentHighSpenders20"></span>%)</p>
                                        <p>当天充值消费大于50元人数: <span id="highSpenders50"></span> (占比: <span id="percentHighSpenders50"></span>%)</p>
                                        <p>当天充值消费大于100元人数: <span id="highSpenders100"></span> (占比: <span id="percentHighSpenders100"></span>%)</p>
                                        <p>当天消费人数: <span id="totalConsumers"></span></p>
                                        <p>游戏中消费人数大于20%登录人数的游戏: <span id="gamesWith20PercentSpenders"></span></p>
                                        <p>有人消费大于100元的游戏: <span id="gamesWith100Spenders"></span></p>
                                    </div>

                                </div>
                            </div> 
                        </div> 
                    </div> 
                </div> 
            </div> 
        </div> 
    </div> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.3.3/echarts.min.js"></script>

    <script>
        layui.use(['laydate'], function(){
            var laydate = layui.laydate;

            laydate.render({
                elem: '#date',
                type: 'date',
                format: 'yyyy-MM-dd',
                value: new Date().toISOString().slice(0, 10),
                done: function(value) {
                    fetchData(value);
                }
            });

            fetchData(new Date().toISOString().slice(0, 10));
        });

        let charts = {};
        let cache = {};

        $(document).ready(function() {
            charts = renderCharts();
        });

        async function fetchData(date) {
            if (cache[date]) {
                updateCharts(cache[date]);
                updateStatistics(cache[date].highSpendersData);
                updateTotalRechargeStatistics(cache[date].totalRechargeData);
                return;
            }

            const urls = [
                { url: '{{ route("admin.dashboard.rechargePieData") }}', id: 'pieData' },
                { url: '{{ route("admin.dashboard.dayBarData") }}', id: 'dayBarData' },
                { url: '{{ route("admin.dashboard.recentGamesBarData") }}', id: 'recentGamesBarData' },
                { url: '{{ route("admin.dashboard.monthlyBarData") }}', id: 'monthlyBarData' },
                { url: '{{ route("admin.dashboard.redPacketBarData") }}', id: 'redPacketBarData' },
                { url: '{{ route("admin.dashboard.loginPieData") }}', id: 'loginPieData' },
                { url: '{{ route("admin.dashboard.highSpendersData") }}', id: 'highSpendersData' },
                { url: '{{ route("admin.dashboard.totalRechargeData") }}', id: 'totalRechargeData' },
            ];

            try {
                const promises = urls.map(urlObj => 
                    $.ajax({
                        url: urlObj.url,
                        method: 'GET',
                        data: { date: date },
                    }).then(response => ({ id: urlObj.id, data: response }))
                );

                const results = await Promise.all(promises);

                const data = results.reduce((acc, result) => {
                    acc[result.id] = result.data;
                    return acc;
                }, {});

                cache[date] = data;

                updateCharts(data);
                updateStatistics(data.highSpendersData);
                updateTotalRechargeStatistics(data.totalRechargeData);
            } catch (error) {
                console.error('获取数据失败', error);
            }
        }

        function renderCharts() {
            const pieChart = echarts.init(document.getElementById('pieChart'), null, {renderer: 'canvas'});
            // const dayBarChart = echarts.init(document.getElementById('dayBarChart'), null, {renderer: 'canvas'});
            const recentGamesBarChart = echarts.init(document.getElementById('recentGamesBarChart'), null, {renderer: 'canvas'});
            const monthlyBarChart = echarts.init(document.getElementById('monthlyBarChart'), null, {renderer: 'canvas'});
            // const redPacketChart = echarts.init(document.getElementById('redPacketChart'), null, {renderer: 'canvas'});
            const loginPieChart = echarts.init(document.getElementById('loginPieChart'), null, {renderer: 'canvas'});
            const totalRechargeChart = echarts.init(document.getElementById('totalRechargeChart'), null, {renderer: 'canvas'});

            return { pieChart, recentGamesBarChart, monthlyBarChart, loginPieChart, totalRechargeChart };
        }

        function updateCharts(data) {
            const pieOption = {
                title: { text: `当天所有游戏有充值金额的环状图及占比 (总充值金额: ${data.pieData.totalAmount})`, left: 'center' },
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        const percent = ((params.value / data.pieData.totalAmount) * 100).toFixed(2);
                        return `${params.name}<br/>充值金额: ${params.value} (${percent}%)`;
                    }
                },
                series: [{ name: '充值金额', type: 'pie', radius: ['40%', '70%'], data: data.pieData.pieData }]
            };

            const dayBarOption = {
                title: { text: '当日所有游戏充值金额前10名排行', left: 'center', top: '10px' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                legend: { data: ['充值金额', '充值人数', '大于20元人数', '大于50元人数'], top: 'bottom' },
                xAxis: { type: 'category', data: data.dayBarData.names.slice(0, 10) },
                yAxis: { type: 'value' },
                series: [
                    { name: '充值金额', type: 'bar', data: data.dayBarData.values.slice(0, 10), itemStyle: { color: '#5470C6' } },
                    { name: '充值人数', type: 'bar', data: data.dayBarData.login_counts.slice(0, 10), itemStyle: { color: '#91CC75' } },
                    { name: '大于20元人数', type: 'bar', data: data.dayBarData.high_spenders.slice(0, 10), itemStyle: { color: '#EE6666' } },
                    { name: '大于50元人数', type: 'bar', data: data.dayBarData.high_spenders_50.slice(0, 10), itemStyle: { color: '#FFCC33' } }
                ]
            };

            const recentGamesBarOption = {
                title: { text: '最近7个游戏近3日游戏充值柱状图', left: 'center' },
                legend: { data: data.recentGamesBarData.names, top: 'bottom' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                xAxis: { type: 'category', data: ['前天', '昨天', '今天'] },
                yAxis: { type: 'value' },
                series: data.recentGamesBarData.values.map((gameData, index) => ({
                    name: gameData.name,
                    type: 'bar',
                    data: gameData.values,
                    itemStyle: { color: echarts.color.random() }
                }))
            };

            const monthlyBarOption = {
                title: { text: '当月1号起到当日所有游戏的充值金额汇总统计柱状图', left: 'center' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                xAxis: { type: 'category', data: data.monthlyBarData.names },
                yAxis: { type: 'value' },
                series: [{ name: '充值金额', type: 'bar', data: data.monthlyBarData.values, itemStyle: { color: echarts.color.random() } }]
            };

            const redPacketOption = {
                title: { text: '最近5个红包版本近3日充值金额数据', left: 'center' },
                legend: { data: data.redPacketBarData.names, top: 'bottom' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                xAxis: { type: 'category', data: ['前天', '昨天', '今天'] },
                yAxis: { type: 'value' },
                series: data.redPacketBarData.values.map((packetData, index) => ({
                    name: packetData.name,
                    type: 'bar',
                    data: packetData.values,
                    itemStyle: { color: echarts.color.random() }
                }))
            };

            const loginPieOption = {
                title: { text: `当天所有游戏的登录人数环状图及占比 (总登录人数: ${data.loginPieData.totalLogins})`, left: 'center', top: '10px' },
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        const percent = ((params.value / data.loginPieData.totalLogins) * 100).toFixed(2);
                        return `${params.name}<br/>登录人数: ${params.value} (${percent}%)`;
                    }
                },
                series: [{ name: '登录人数', type: 'pie', radius: ['40%', '70%'], data: data.loginPieData.loginPieData }]
            };

            const totalRechargeOption = {
                title: { text: '所有游戏历史总充值和当月总充值', left: 'center' },
                tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
                legend: { data: ['历史总充值', '当月总充值', '当月占比'], top: 'bottom' },
                xAxis: { type: 'category', data: data.totalRechargeData.totalRechargeData.map(item => item.version_name) },
                yAxis: { type: 'value' },
                series: [
                    { name: '历史总充值', type: 'bar', data: data.totalRechargeData.totalRechargeData.map(item => item.total_amount), itemStyle: { color: '#5470C6' } },
                    { name: '当月总充值', type: 'bar', data: data.totalRechargeData.totalRechargeData.map(item => item.monthly_amount), itemStyle: { color: '#91CC75' } },
                    { name: '当月占比', type: 'line', data: data.totalRechargeData.totalRechargeData.map(item => item.monthly_percentage), itemStyle: { color: '#EE6666' } }
                ]
            };

            charts.pieChart.setOption(pieOption, { notMerge: true, lazyUpdate: true });
            // charts.dayBarChart.setOption(dayBarOption, { notMerge: true, lazyUpdate: true });
            charts.recentGamesBarChart.setOption(recentGamesBarOption, { notMerge: true, lazyUpdate: true });
            charts.monthlyBarChart.setOption(monthlyBarOption, { notMerge: true, lazyUpdate: true });
            // charts.redPacketChart.setOption(redPacketOption, { notMerge: true, lazyUpdate: true });
            charts.loginPieChart.setOption(loginPieOption, { notMerge: true, lazyUpdate: true });
            charts.totalRechargeChart.setOption(totalRechargeOption, { notMerge: true, lazyUpdate: true });
        }

        function updateStatistics(data) {
            $('#highSpenders20').text(data.highSpenders20);
            $('#percentHighSpenders20').text(data.percentHighSpenders20);
            $('#highSpenders50').text(data.highSpenders50);
            $('#percentHighSpenders50').text(data.percentHighSpenders50);
            $('#highSpenders100').text(data.highSpenders100);
            $('#percentHighSpenders100').text(data.percentHighSpenders100);
            $('#totalConsumers').text(data.totalConsumers);

            let gamesWith20PercentSpenders = data.gamesWith20PercentSpenders.map(game => `${game.version_name}: ${game.spenders}`).join(', ');
            let gamesWith100Spenders = data.gamesWith100Spenders.map(game => `${game.version_name}: ${game.spenders}`).join(', ');

            $('#gamesWith20PercentSpenders').text(gamesWith20PercentSpenders);
            $('#gamesWith100Spenders').text(gamesWith100Spenders);
        }

        function updateTotalRechargeStatistics(data) {
            $('#totalMonthlyAmount').text(data.totalMonthlyAmount);
            $('#totalOverallAmount').text(data.totalOverallAmount);
        }
    </script>
</body>

<style>
    .layui-input {
        display: inline-block;
    }
</style>
</html>
